<template>
  <base-modal
    :show="visible"
    :title="$t('setting.enterprise.accountLoginSettingsText13')"
    width="800px"
    @cancel="visible = false"
  >
    <el-form
      ref="ssoRuleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="top"
    >
      <el-row class="sso-divider">{{ $t('setting.enterprise.accountLoginSettingsText10') }}</el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField1')"
            prop="clientId"
          >
            <el-input
              v-model="ruleForm.clientId"
              :placeholder="$t('common.base.tip.defaultPlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField2')"
            prop="clientSecret"
          >
            <el-input
              v-model="ruleForm.clientSecret"
              :placeholder="$t('common.base.tip.defaultPlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField3')"
            prop="codeUrl"
          >
            <el-input
              v-model="ruleForm.codeUrl"
              :placeholder="$t('setting.enterprise.accountLoginSettingsVal2')"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField4')"
            prop="tokenUrl"
          >
            <el-input
              v-model="ruleForm.tokenUrl"
              :placeholder="$t('setting.enterprise.accountLoginSettingsVal2')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="sso-divider mar-t-12">{{ $t('setting.enterprise.accountLoginSettingsText11') }}</el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField5')"
            prop="userUrl"
          >
            <el-input
              v-model="ruleForm.userUrl"
              :placeholder="$t('setting.enterprise.accountLoginSettingsVal2')"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField6')"
            prop="tokenExpireValue"
          >
            <div :style="{display: 'flex'}">
              <el-input
                v-model="ruleForm.tokenExpireValue"
                class="mar-r-12"
                :placeholder="$t('common.base.tip.defaultPlaceholder')"
                type="number"
              ></el-input>
              <el-select
                v-model="ruleForm.tokenExpireUnit"
                :placeholder="$t('common.base.pleaseSelect')"
                :style="{width: '100%'}"
              >
                <el-option
                  :label="$t('common.base.hour1')"
                  value="h"
                ></el-option>
                <el-option
                  :label="$t('common.base.day')"
                  value="d"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField7')"
            prop="userFieldName"
          >
            <el-select
              v-model="ruleForm.userFieldName"
              :placeholder="$t('common.base.pleaseSelect')"
              :style="{width: '100%'}"
            >
              <el-option
                label="工号"
                value="workNo"
              ></el-option>
              <el-option
                :label="$t('common.label.accountNumber')"
                value="loginName"
              ></el-option>
              <el-option
                :label="$t('common.fields.email.displayName')"
                value="email"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField8')"
            prop="userFieldValue"
          >
            <el-input
              v-model="ruleForm.userFieldValue"
              :placeholder="$t('setting.enterprise.accountLoginSettingsVal3')"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item
            :label="$t('setting.enterprise.accountLoginSettingsField9')"
            prop="redirectUri"
          >
            <div class="redirect-copy">
              <span>{{ ruleForm.redirectUri }}</span>
              <i
                v-if="ruleForm.redirectUri.length > 0"
                @click='copyRedirectUrl(ruleForm.redirectUri)'
                class="iconfont icon-qiehuan"
              ></i>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button @click="closeDialog">{{$t('common.base.cancel')}}</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="onSubmit"
      >
        {{$t('common.base.confirm')}}
      </el-button>
    </div>
  </base-modal>
</template>
<script>
import { defineComponent, ref, reactive, toRefs } from 'vue';
import { setClipboardData } from '@src/util/dom';

import { toast } from '@src/util/platform';
import i18n from '@src/locales';

export default defineComponent({
  setup(props, { emit }) {
    const visible = ref(false);
    const ssoRuleFormRef = ref(false);
    const loading = ref(false);

    const validateURL = url => {
      // 使用正则表达式验证URL是否以http或https开头
      const regex = /^(http|https):\/\//;
      return regex.test(url);
    };

    const validateStartsWithDollarDot = value => {
      const regex = /^\$\./;
      return regex.test(value);
    };

    // 通用的URL验证器
    const createURLValidator = message => {
      return (rule, value, callback) => {
        if (!value) {
          callback(new Error(`${message}`));
        } else if (!validateURL(value)) {
          callback(new Error(i18n.t('setting.enterprise.accountLoginSettingsVal2')));
        } else {
          callback();
        }
      };
    };

    const validator1 = (rule, value, callback) => {
      if (!value) {
        callback(new Error(i18n.t('setting.enterprise.accountLoginSettingsVal1')));
      } else if (!validateStartsWithDollarDot(value)) {
        callback(new Error(i18n.t('setting.enterprise.accountLoginSettingsVal3')));
      } else {
        callback();
      }
    };
    const state = reactive({
      ruleForm: {
        clientId: '',
        clientSecret: '',
        codeUrl: '',
        tokenUrl: '',
        tokenExpireValue: '',
        tokenExpireUnit: 'h',
        userUrl: '',
        userFieldName: '',
        userFieldValue: '',
        redirectUri: '',
      },
      rules: {
        clientId: [{ required: true, message: i18n.t('setting.enterprise.accountLoginSettingsVal4'), trigger: 'blur' }],
        clientSecret: [{ required: true, message: i18n.t('setting.enterprise.accountLoginSettingsVal5'), trigger: 'blur' }],
        codeUrl: [{ required: true, validator: createURLValidator(i18n.t('setting.enterprise.accountLoginSettingsVal6')), trigger: 'blur' }],
        tokenUrl: [{ required: true, validator: createURLValidator(i18n.t('setting.enterprise.accountLoginSettingsVal7')), trigger: 'blur' }],
        tokenExpireValue: [{ required: true, message: i18n.t('setting.enterprise.accountLoginSettingsVal8'), trigger: 'blur' }],
        userUrl: [{ required: true, message: i18n.t('setting.enterprise.accountLoginSettingsVal9'), trigger: 'blur' }],
        userFieldName: [{ required: true, message: i18n.t('setting.enterprise.accountLoginSettingsVal11'), trigger: 'blur' }],
        userFieldValue: [{ required: true, validator: validator1, trigger: 'blur' }],
      },
    });

    const openDialog = row => {
      visible.value = true;
      state.ruleForm = {
        ...row,
        tokenExpireUnit: row?.tokenExpireUnit || 'h',
        redirectUri: row?.redirectUri || '',
      };
    };

    const closeDialog = () => {
      visible.value = false;
      loading.value = false;
      ssoRuleFormRef.value.resetFields();
    };

    const onSubmit = () => {
      ssoRuleFormRef.value.validate(valid => {
        if (valid) {
          loading.value = true;
          emit('submitLoginInfo', {
            params: state.ruleForm,
            type: 'sso',
            callBack: () => {
              closeDialog();
            },
          });
        }
      });
    };

    const copyRedirectUrl = text => {
      setClipboardData(
        text,
        () => {
          toast(i18n.t('common.base.tip.copySuccess'), 'success');
        },
        () => {
          toast(i18n.t('common.base.tip.copySuccess'), 'error');
        }
      );
    };
    return {
      visible,
      ssoRuleFormRef,
      loading,
      ...toRefs(state),
      openDialog,
      closeDialog,
      onSubmit,
      copyRedirectUrl,
    };
  },
});
</script>
<style lang="scss" scoped>
.sso-divider {
  font-size: 14px;
  font-weight: 500;
  padding: 8px 12px;
  background: #f0f2f5;
  border-radius: 4px;
  margin-bottom: 16px;
}
.redirect-copy {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 32px;
  border: 1px solid #e4e7ed;
  background: #f5f7fa;
  border-radius: 4px;
  padding: 0 12px;
  color: #262626;
  cursor: pointer;
  @include text-ellipsis();
}
</style>
